package com_.dxy_test_.reflect_;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Description 测试反射
 * @Author dangxianyue
 * @Date 2024/3/7 16:36
 */
public class MyClass {

    private String message;

    static {
        System.out.println("我是静态代码块，在类加载时执行！");
    }

    public MyClass() {
        this.message = "xxx";
        System.out.println("我是无参构造函数！");
    }

    public MyClass(final String message) {
        this.message = message;
        System.out.println("我是有参构造函数！");
    }

    public void printMessage() {
        System.out.println("我是实例方法！message=" + this.message);
    }

    public static void main(String[] args) {
        try {

            System.out.println("step1=================");
            // 使用 Class.forName() 方法获取类的 Class 对象，此步就会执行static代码快
            Class<?> myClass = Class.forName("com_.dxy_test_.reflect_.MyClass");

            System.out.println("step2=================");
            // 获取无参构造函数
            Constructor<?> constructor = myClass.getDeclaredConstructor();
            // 使用无参构造函数创建对象
            MyClass obj1 = (MyClass) constructor.newInstance();
            obj1.printMessage();

            System.out.println("step3=================");
            // 获取带参数的构造函数
            Constructor<?> paramConstructor = myClass.getDeclaredConstructor(String.class);
            // 使用带参数的构造函数创建对象
            MyClass obj2 = (MyClass) paramConstructor.newInstance("Hello, Reflection with parameter!");
            obj2.printMessage();

        } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException |
                IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
